package com.rongke.wxPayUtil.wxRefundUtil.wechat;


import com.rongke.wxPayUtil.config.WXpayConfig;
import com.rongke.wxPayUtil.util.WXpayXmlUtils;
import com.rongke.wxPayUtil.wxRefundUtil.wx.ClientCustomSSL;
import com.rongke.wxPayUtil.wxRefundUtil.wx.RequestHandler;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;


public class RefundUtil {
//    public static String p12Path=RefundUtil.class.getResource("apiclient_cert.p12").getFile();
	public static Map<String,String> wechatRefund(String out_trade_no, String total_fee, String refund_fee,String apiUrl) {
		//api地址：http://mch.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4
		String str=UUID.randomUUID().toString().replaceAll("-", "").toLowerCase().substring(0,32);
		String out_refund_no = str;// 退款单号
		String nonce_str = "4232343765";// 随机字符串
		String appid = WXpayConfig.appid; //微信公众号apid
		String appsecret = WXpayConfig.api_key; //微信公众号appsecret
		String mch_id = WXpayConfig.mch_id;  //微信商户id
		String op_user_id =WXpayConfig.mch_id;//就是MCHID
		String partnerkey = WXpayConfig.api_key;//API 密钥
		SortedMap<String, String> packageParams = new TreeMap<String, String>();
		packageParams.put("appid", appid);
		packageParams.put("mch_id", mch_id);
		packageParams.put("nonce_str", nonce_str);
		packageParams.put("out_trade_no", out_trade_no);
		packageParams.put("out_refund_no", out_refund_no);
		packageParams.put("total_fee", total_fee);
		packageParams.put("refund_fee", refund_fee);
		packageParams.put("op_user_id", op_user_id);
		RequestHandler reqHandler = new RequestHandler(
				null, null);
		reqHandler.init(appid, appsecret, partnerkey);

		String sign = reqHandler.createSign(packageParams);
		String xml = "<xml>" + "<appid>" + appid + "</appid>" + "<mch_id>"
				+ mch_id + "</mch_id>" + "<nonce_str>" + nonce_str
				+ "</nonce_str>" + "<sign><![CDATA[" + sign + "]]></sign>"
				+ "<out_trade_no>" + out_trade_no + "</out_trade_no>"
				+ "<out_refund_no>" + out_refund_no + "</out_refund_no>"
				+ "<total_fee>" + total_fee + "</total_fee>"
				+ "<refund_fee>" + refund_fee + "</refund_fee>"
				+ "<op_user_id>" + op_user_id + "</op_user_id>" + "</xml>";
		String createOrderURL = "https://api.mch.weixin.qq.com/secapi/pay/refund";
		String xmlStr=null;
		try {
			xmlStr= ClientCustomSSL.doRefund(createOrderURL, xml,apiUrl);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Map<String, String> map=null;
		if(xmlStr!=null){
			map= WXpayXmlUtils.xml2map(xmlStr);
		}
		return map;
	}


	public static void main(String[] args) {
		RefundUtil refund=new RefundUtil();
		Map<String, String> map=refund.wechatRefund("176accfa2db9ef89422d9fe3fce9fdab","1","1","");
		System.out.print(map);
	}


}
